package thread;

import java.util.Random;

public class ThreadUse {
    //定义为静态成员变量
    private static int sum1 = 0;
    private static int sum2 = 0;

    public static void main(String[] args) throws InterruptedException {
        final int[] array = new int[1000_0000];
        //生成1-100随机数
        Random random = new Random();
        for (int i = 0; i < array.length; i++) {
            array[i] = random.nextInt(100) + 1;//[0-100)+1=[1,100]
        }
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < array.length; i += 2) {
                sum1 += array[i];
            }
            System.out.println("偶数下标元素之和为：" + sum1);
        });
        Thread t2 = new Thread(() -> {
            for (int i = 1; i < array.length; i += 2) {
                sum2 += array[i];
            }
            System.out.println("奇数下标元素之和为：" + sum2);
        });
        long beg = System.currentTimeMillis();
        //线程启动
        t1.start();
        t2.start();
        //阻塞当前线程 让main线程等待t1 t2线程结束
        t1.join();
        t2.join();
        long end = System.currentTimeMillis();
        int totalSum = sum1 + sum2;
        System.out.println("总和: " + totalSum);
        System.out.println("程序执行时间为："+(end-beg)+"ms");
    }
}
